package role

import (
	"github.com/infraboard/mcube/pb/resource"
)

func NewRole(spec *RoleSpec) *Role {
	return &Role{
		Meta: resource.NewMeta(),
		Spec: spec,
	}
}

func (r *Role) HasPerm(service, resource, action string) bool {
	for i := range r.Spec.Permissons {
		perm := r.Spec.Permissons[i]
		if perm.HasPerm(service, resource, action) {
			return true
		}
	}
	return false
}

func (p *Permission) HasPerm(service, resource, action string) bool {
	// 首先判断服务
	if p.Service != "*" && p.Service != service {
		return false
	}

	if p.Resource != "*" && p.Resource != resource {
		return false
	}

	if !p.HasAction(action) {
		return false
	}

	return true
}

func (p *Permission) HasAction(aciton string) bool {
	for i := range p.Action {
		a := p.Action[i]
		if a == "*" || a == aciton {
			return true
		}
	}

	return false
}
